package com.zjh.es;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

@SpringBootTest
public class DocumentAggregationsQuery {
    @Autowired
    private RestHighLevelClient client;
    @Test
    void testAggregations() throws IOException {
        SearchRequest searchRequest = new SearchRequest("fruit");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//        sourceBuilder.aggregation(AggregationBuilders.max("max_price").field("price"));
        sourceBuilder.aggregation(AggregationBuilders.terms("price_group").field("price"));
        searchRequest.source(sourceBuilder);
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println(search.getAggregations());
    }
    /**
     * 过滤聚合
     */
    @Test
    void testAggregations2() throws IOException {

        SearchRequest searchRequest = new SearchRequest("fruit");

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(QueryBuilders.boolQuery().filter(QueryBuilders.rangeQuery("price").lte(20)))
                        .aggregation(AggregationBuilders.avg("price_avg").field("price"));

        searchRequest.source(sourceBuilder);
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println(search);
    }
    /**
     * 多级聚合
     */
    @Test
    void testAggregations3() throws IOException {

        SearchRequest searchRequest = new SearchRequest("items");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("brand_groupBy").field("brand");

        sourceBuilder.aggregation(AggregationBuilders.terms("category_groupBy").field("category").subAggregation(termsAggregationBuilder));

        searchRequest.source(sourceBuilder);
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println(search);
    }
}
